<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>Java web:请求与响应 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-05-02 09:28">
      May 2, 2019 am
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.5k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      34
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-Java-web之请求与响应"><a href="#学习笔记-Java-web之请求与响应" class="headerlink" title="学习笔记 : Java web之请求与响应"></a>学习笔记 : Java web之请求与响应</h2><h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p><em><code>Servlet</code>最主要的作用就是处理客户端请求,并向客户端做出响应.为此,针对Servlet的每次请求,Web服务器在调用<code>service()</code>之前,都会创建两个对象,分别是: <code>HttpServletRequest</code>和<code>HttpServletResponse</code>.其中HttpServletRequest用于封装HTTP请求消息,简称<code>request</code>对象.HttpServletResponse用于封装HTTP响应消息,简称<code>response</code>对象.下面通过示例图来展示浏览器访问Servlet的交互过程.</em></p>
<p><img src="/2019/05/02/Java-web-%E8%AF%B7%E6%B1%82%E4%B8%8E%E5%93%8D%E5%BA%94/%E6%B5%8F%E8%A7%88%E5%99%A8%E8%AE%BF%E9%97%AEServlet%E7%9A%84%E4%BA%A4%E4%BA%92%E8%BF%87%E7%A8%8B.png" srcset="/img/loading.gif" alt=" "></p>
<h3 id="HttpServletResponse"><a href="#HttpServletResponse" class="headerlink" title="HttpServletResponse"></a>HttpServletResponse</h3><p><em>HttpServletResponse接口继承自<code>ServletResponse</code>,用于封装HTTP响应消息.由于HTTP响应消息分为 : <code>状态行</code>,<code>响应消息头</code>,<code>消息体</code>三部分,因此,在HttpServletResponse接口中定义了向客户端发送响应状态码,响应消息头,响应消息体的方法.</em></p>
<h3 id="HttpServletResponse-application"><a href="#HttpServletResponse-application" class="headerlink" title="HttpServletResponse application"></a>HttpServletResponse application</h3><h4 id="中文输出乱码问题"><a href="#中文输出乱码问题" class="headerlink" title="中文输出乱码问题"></a>中文输出乱码问题</h4><p><em>由于计算机中的数据都是以二进制形式存储的,因此,当传输文本时,就会发生字符和字节之间的转换.字符与字节之间是通过查码表完成的,将字符转换为字节的过程称为<code>编码</code>,相反称为<code>解码</code>.如果两者使用的码表不一致就会导致乱码问题.可通过以下示例程序中的方法解决此问题.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/SetCharsetServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SetCharsetServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SetCharsetServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		<span class="hljs-comment">// 第一种解决乱码的方式</span>
		<span class="hljs-comment">// response.setCharacterEncoding("utf-8");</span>
		<span class="hljs-comment">// response.setHeader("Content-Type", "text/html;charset=utf-8");</span>

		<span class="hljs-comment">// 第二种解决乱码的方式</span>
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		PrintWriter printWriter = response.getWriter();
		printWriter.write(<span class="hljs-string">"中文"</span>);
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>

<h4 id="网页定时刷新并跳转"><a href="#网页定时刷新并跳转" class="headerlink" title="网页定时刷新并跳转"></a>网页定时刷新并跳转</h4><p><em>在HTTP中定义了一个<code>Refresh</code>头字段,他可以通知浏览器在指定的时间自动刷新并跳转到其它页面.示例程序如下.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/SetHeaderServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SetHeaderServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SetHeaderServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		<span class="hljs-comment">// 实现网页的定时刷新并跳转</span>
		response.setHeader(<span class="hljs-string">"Refresh"</span>,<span class="hljs-string">"5;URL=https://yubuntu0109.github.io"</span>);

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>

<h4 id="请求重定向"><a href="#请求重定向" class="headerlink" title="请求重定向"></a>请求重定向</h4><p><em>在某些情况下,针对客户端的请求,一个<code>Servlet</code>类可能无法完成全部工作.这时,可以使用请求重定向来完成.所谓的请求重定向,指的是Web服务器接受到客户端的请求后,可能由于某些条件限制,不能访问当前请求URL所指的Web资源,而是指定了一个新的资源路径,让客端户重新发送请求.</em></p>
<ol>
<li><p><em>用户登录界面</em></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">%@</span> <span class="hljs-attr">page</span> <span class="hljs-attr">language</span>=<span class="hljs-string">"java"</span> <span class="hljs-attr">contentType</span>=<span class="hljs-string">"text/html; charset=UTF-8"</span>
    <span class="hljs-attr">pageEncoding</span>=<span class="hljs-string">"UTF-8"</span>%&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE html&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>login in<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>User login interface<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">hr</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"SendRedirectTest"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
					<span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
						<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>User name<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
						<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>/&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
					<span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
					<span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
						<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
						<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"userpassword"</span>/&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
					<span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
				<span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"login in"</span>/&gt;</span>
			<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
		<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre></div>
</li>
<li><p><em>登录成功页面</em></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">%@</span> <span class="hljs-attr">page</span> <span class="hljs-attr">language</span>=<span class="hljs-string">"java"</span> <span class="hljs-attr">contentType</span>=<span class="hljs-string">"text/html; charset=UTF-8"</span>
    <span class="hljs-attr">pageEncoding</span>=<span class="hljs-string">"UTF-8"</span>%&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE html&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>success<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span> &gt;</span>weclome<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">hr</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>success to login in !<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre></div>
</li>
<li><p><em>编写处理用户登录请求的Servlet程序</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/SendRedirectServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SendRedirectServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SendRedirectServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		<span class="hljs-comment">// 设置编码</span>
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		<span class="hljs-comment">// 使用HttpServletRequest对象的getParameter()方法获取用户名及密码</span>
		String name = request.getParameter(<span class="hljs-string">"username"</span>);
		String password = request.getParameter(<span class="hljs-string">"userpassword"</span>);

		<span class="hljs-keyword">if</span> (<span class="hljs-string">"YUbuntu0109"</span>.equals(name) &amp;&amp; <span class="hljs-string">"demo"</span>.equals(password)) &#123;
			response.sendRedirect(<span class="hljs-string">"Redirection/welcome.jsp"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			response.sendRedirect(<span class="hljs-string">"login.jsp"</span>);
		&#125;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>


</li>
</ol>
<h3 id="HttpServletRequest"><a href="#HttpServletRequest" class="headerlink" title="HttpServletRequest"></a>HttpServletRequest</h3><p><em>HttpServletRequest接口继承自<code>ServletRequest</code>,用于封装HTTP请求消息.由于HTTP请求消息分为 : <code>请求行</code>,<code>请求消息头</code>,<code>请求消息体</code>三部分,因此,在HttpServletRequest接口中定义了获取请求行,请求头,请求消息体的相关方法.</em></p>
<h3 id="HttpServletRequest-application"><a href="#HttpServletRequest-application" class="headerlink" title="HttpServletRequest application"></a>HttpServletRequest application</h3><h4 id="利用Referer请求头防止盗链"><a href="#利用Referer请求头防止盗链" class="headerlink" title="利用Referer请求头防止盗链"></a>利用Referer请求头防止盗链</h4><p><em>编写一个Servlet类,其负责提供下载内容,但它要求下载请求的链接必须是通过本网站进入的,否则,会将请求转发给下载说明的HTML页面.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: DownManagerServlet
 * <span class="hljs-doctag">@Description</span>: 利用`Referer`请求头防止盗链
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 9:41:11 AM
 *
 */</span>
<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/DownManagerServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DownManagerServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DownManagerServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);
		PrintWriter printWriter = response.getWriter();

        <span class="hljs-comment">// 获取referer头的值: http://localhost:8080/Request-Response_basic/DownManagerServlet</span>
		String referer = request.getHeader(<span class="hljs-string">"referer"</span>);

        <span class="hljs-comment">// 获取访问地址</span>
		<span class="hljs-comment">// 由于第一次请求DownManagerServlet时,请求消息中并不包含referer请求头,</span>
		<span class="hljs-comment">// 所以DownManagerServlet会将下载请求转发给了downlaod.html页面</span>
		String sitePart = <span class="hljs-string">"http://"</span> + request.getServerName();

		<span class="hljs-keyword">if</span> (referer != <span class="hljs-keyword">null</span> &amp;&amp; referer.startsWith(sitePart)) &#123;
			printWriter.println(<span class="hljs-string">"dealing download ..."</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;

			<span class="hljs-comment">// 非法下载请求将跳转到download.html页面</span>
			request.getRequestDispatcher(<span class="hljs-string">"HttpServletRequest/download.html"</span>).forward(request, response);
		&#125;

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>

<h4 id="请求参数的中文乱码问题"><a href="#请求参数的中文乱码问题" class="headerlink" title="请求参数的中文乱码问题"></a>请求参数的中文乱码问题</h4><p><em>HttpServletRequest接口中,提供了一个<code>setCharacterEncoding()</code>方法,该方法用于设置request对象的解码方式.但该方法只对<code>POST</code>提交方式有效(<code>错误结论</code>),为了解决<code>GET</code>方式提交表单的中文乱码问题,可以首先使用<code>ISO 8859-1</code>将用户名重新编码,然后使用码表GBK进行解码.示例程序略..</em></p>
<h3 id="RequestDispatcher"><a href="#RequestDispatcher" class="headerlink" title="RequestDispatcher"></a>RequestDispatcher</h3><p><em>当一个Web资源收到客户端的请求后,如果希望服务器通知另外一个资源去处理请求,这时,除了使用<code>sendRedirect()</code>方法实现请求重定向外,还可以通过<code>RequestDispatcher</code>接口的实例对象来实现.在<code>ServletRequest</code>接口中定义了一个获取RequestDispatcher对象的方法.</em></p>
<ol>
<li><p><em>获取RequestDispatcher对象的方法</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">// 返回封装了某个路径所指资源的RequestDispather对象.其中,参数path必须</span>
<span class="hljs-comment">// 以'/'开头,用于表示当前Web应用的根目录</span>
getRequestDispatcher(String path);</code></pre></div>
</li>
<li><p><em>获取RequestDispatcher对象后,最重要的工作是通知其他Web资源处理当前的Servlet请求,为此,在RequestDispather接口中,定义了两个相关的方法</em></p>
<div class="hljs"><pre><code class="hljs java">// 该方法用于将请求从一个Servlet传递给另外的一个Web资源(请求转发)
// 注意: 该方法必须在响应提交给客户端之前被调用,否则抛出IllegalStateException
forward(ServletRequests request,ServletResponse response);

// 该方法用于将其他的资源作为当前响应内容包含进来
include(ServletRequest request,ServletResponse response);
``` 

### RequestDispatcher applicatoin

#### forward()实现请求转发
*通过使用`forward()`方法,将当前RequestForwardServlet的请求转发到ResultServlet页面*

1. *RequestForwardServlet示例程序*
```java
/**
 * @ClassName: RequestForwardServlet
 * @Description: 请求转发:forword()
 * @author: HuangYuhui
 * @date: Apr 29, 2019 11:07:03 AM
 *
 */
@WebServlet("/RequestForwardServlet")
public class RequestForwardServlet extends HttpServlet &#123;
	private static final long serialVersionUID = 1L;

	public RequestForwardServlet() &#123;
		super();
	&#125;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException &#123;

		response.setContentType("text/html;charset=utf-8");
		request.setAttribute("websiteURL", "https://yubuntu0109.github.io");
		// request.getRequestDispatcher("/ResultServlet").forward(request, response);
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("/ResultServlet");
		requestDispatcher.forward(request, response);

	&#125;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException &#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div></li>
<li><p><em>ResultServlet示例程序</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: ResultServlet
 * <span class="hljs-doctag">@Description</span>: 请求转发:forword()
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 11:12:47 AM
 *
 */</span>
<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/ResultServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResultServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ResultServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);
		response.getWriter().println(<span class="hljs-string">"&lt;p align='center'&gt;"</span> + <span class="hljs-string">"my personal blog website address : "</span>
				+ request.getAttribute(<span class="hljs-string">"websiteURL"</span>) + <span class="hljs-string">"&lt;/p&gt;"</span>);
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div></li>
<li><p><em>页面显示结果</em></p>
<div class="hljs"><pre><code class="hljs groovy">my personal blog website <span class="hljs-string">address :</span> <span class="hljs-string">https:</span><span class="hljs-comment">//yubuntu0109.github.io</span></code></pre></div></li>
</ol>
<p><em>由结果可知,<code>forward()</code>方法不仅可以实现请求转发,还可以使转发页面和转发到的页面共享数据.需要注意的是: <code>存储在request对象中的数据只对当前请求有效,而对其他请求无效.</code></em></p>
<h4 id="include-实现请求包含"><a href="#include-实现请求包含" class="headerlink" title="include()实现请求包含"></a>include()实现请求包含</h4><p><em>请求包含指的是使用<code>include</code>方法将Servlet请求转发给其他Web资源进行处理,与请求转发不同的是,在请求包含返回的响应消息中,既包含当前Servlet的响应消息也包含其他Web资源所做出的响应消息.</em></p>
<ol>
<li><p><em>编写IncludingServlet程序,其中调用<code>include()</code>方法请求包含IncludedServlet程序.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: IncludingServlet
 * <span class="hljs-doctag">@Description</span>: 请求包含:include() 
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 11:28:25 AM
 *
 */</span>
<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/IncludingServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IncludingServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">IncludingServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		<span class="hljs-comment">// 因为请求IncludingServelt时,用于封装响应消息的HttpServletResponse对象已经创建,该对象在编码时采用的是默认的: ISO 8859-1</span>
		<span class="hljs-comment">// 所以当客户端对接收到的数据进行解码时,Web服务器会继续保持调用HttpServeltResponse对象中的信息,从而使IncludedServlet中</span>
		<span class="hljs-comment">// 的输出内容发生乱码.为解决此问题需在IncludingServlet中提前设置如下编码方式 .</span>
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		RequestDispatcher resDispatcher = request.getRequestDispatcher(<span class="hljs-string">"/IncludedServelt?name=YUbuntu0109"</span>);
		resDispatcher.include(request, response);
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>IncludedServlet程序</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: IncludedServlet
 * <span class="hljs-doctag">@Description</span>: 请求包含:include()
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 11:33:42 AM
 *
 */</span>
<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/IncludedServelt"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IncludedServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">IncludedServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);
		PrintWriter printWriter = response.getWriter();
		printWriter.println(<span class="hljs-string">"中文&lt;br&gt;"</span>);
		printWriter.println(<span class="hljs-string">"user name : "</span> + request.getParameter(<span class="hljs-string">"name"</span>) + <span class="hljs-string">"&lt;br&gt;"</span>);
		printWriter.println(<span class="hljs-string">"request.getRequestURI() : "</span> + request.getRequestURI());
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>页面显示结果</em></p>
<div class="hljs"><pre><code class="hljs routeros">中文<span class="hljs-built_in">
user </span>name : YUbuntu0109
request.getRequestURI() : /Request-Response_basic/IncludingServlet</code></pre></div></li>
</ol>
<p><em>注意: 使用<code>forward()</code>实现请求转发或使用<code>include()</code>方法实现请求包含后,浏览器显示的<code>URL</code>地址是不会变化的 !</em></p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Java-web/">Java web</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/05/02/Java-web-Filter/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Java web:Filter</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/04/28/VOA-Americans-Favorite-Ting-To-Do/">
                        <span class="hidden-mobile">VOA:Americans`Favorite Thing To Do</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Java web:请求与响应&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
